#!/bin/bash
echo "启动configsvr(启动可能需要一段时间,最好等待>10s)"
ansible configsvr -i inventories/mongodb.local -m shell -a "mongod -f {{mongodb_workspace}}/{{inventory_hostname}}/mongodb.conf &"

echo "启动shard(启动可能需要一段时间,最好等待>30s)"
sleep 20s
ansible shard -i inventories/mongodb.local -m shell -a "mongod -f {{mongodb_workspace}}/{{inventory_hostname}}/mongodb.conf &"

echo "启动router(启动可能需要一段时间,最好等待>10s)"
sleep 40s
ansible router -i inventories/mongodb.local -m shell -a "mongos -f {{mongodb_workspace}}/{{inventory_hostname}}/mongodb.conf &"

#echo "快速初始化集群(可能需要尝试多次)"
#sleep 20s
# 如果是首次启动,需要初始化mongo集群
#ansible router_1 -i inventories/mongodb.local -m shell -a "sh ~/db/mongodb/js/initCluster.sh"

# 也可以分步初始化集群,如下:
echo "初始化configsvr副本集"
sleep 20s
ansible configsvr_1 -i inventories/mongodb.local -m shell -a "mongo --host {{bind_ip}} --port {{mongodb_port}} {{mongodb_workspace}}/js/initReplSet_{{replSet}}.js"

echo "初始化shard副本集(可能要执行多次确保副本集初始化成功)"
sleep 20s
ansible shard0001_1:shard0002_1:shard0003_1 -i inventories/mongodb.local -m shell -a "mongo --host {{bind_ip}} --port {{mongodb_port}} {{mongodb_workspace}}/js/initReplSet_{{replSet}}.js"
echo "向router添加shard"
sleep 20s
ansible router_1 -i inventories/mongodb.local -m shell -a "mongo --host {{bind_ip}} --port {{mongodb_port}} {{mongodb_workspace}}/js/addShard.js"
echo "开启分片"
sleep 20s
ansible router_1 -i inventories/mongodb.local -m shell -a "mongo --host {{bind_ip}} --port {{mongodb_port}} {{mongodb_workspace}}/js/enableSharding.js"


echo "测试分片(执行需要一段时间,最好等待>=30s)"
sleep 40
ansible router_1 -i inventories/mongodb.local -m shell -a "mongo --host {{bind_ip}} --port {{mongodb_port}} {{mongodb_workspace}}/js/testSharding.js"

echo "查看启动状态"
sleep 40s
ansible mongodbcluster -i inventories/mongodb.local -m shell -a "cat {{mongodb_workspace}}/{{inventory_hostname}}/mongodb.pid | xargs ps -cp"

# echo "关闭(关闭可能需要一段时间,最好等待>=30s)"
# sleep 40s
# ansible mongodbcluster -i inventories/mongodb.local -m shell -a "cat {{mongodb_workspace}}/{{inventory_hostname}}/mongodb.pid | xargs kill -2"
